﻿using System;
using System.ComponentModel;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Win.Templates.ActionContainers;
using DevExpress.XtraBars;
using DevExpress.ExpressApp;
using Hdt.TransOcean.Dal;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System.Windows.Forms;
using System.Data;
using DevExpress.XtraEditors;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Views.Layout.Modes;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Controls;

namespace Hdt.TransOcean.Presentation
{
    public partial class FormReportCongNo : DevExpress.ExpressApp.Win.Templates.XtraFormTemplateBase, ISupportClassicToRibbonTransform
    {
        private EOperation opt;
        //private int lengthCode = 4;
        //private int invoiceType = 1; // hoa don ban
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            CheckTransformToRibbon();
        }
        protected override IModelFormState GetFormStateNode()
        {
            if (View != null)
            {
                return TemplatesHelper.GetFormStateNode(View.Id);
            }
            else
            {
                return base.GetFormStateNode();
            }
        }
        public override void SetSettings(IModelTemplate modelTemplate)
        {
            base.SetSettings(modelTemplate);
            formStateModelSynchronizerComponent.Model = GetFormStateNode();
        }
        [Obsolete("Use the DetailViewForm() constructor"), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public FormReportCongNo(XafApplication application) : this() { }
        public FormReportCongNo()
        {
            InitializeComponent();
        }

        public FormReportCongNo(EOperation operation, Invoice invoice = null)
        {
            InitializeComponent();
            this.opt = operation;
        }

        private void CreateGrid()
        {
            //DataTable tb = new DataTable();
            //tb.Columns.Add("code");
            //tb.Columns.Add("ticket_code");
            //tb.Columns.Add("invoiced_date");
            //tb.Columns.Add("journey_code");
            //tb.Columns.Add("customer_code");
            //tb.Columns.Add("customer_name");
            //tb.Columns.Add("customer_address");
            //tb.Columns.Add("mobile");
            //tb.Columns.Add("created_date");
            //tb.Columns.Add("airline_code");
            //tb.Columns.Add("sale_price");
            //tb.Columns.Add("saleman");
            //tb.Columns.Add("total_amount");
            //tb.Columns.Add("commission");
            //tb.Columns.Add("passenger_name");
            //tb.Columns.Add("description");
            //tb.Columns.Add("fffff");
            //gridControlBaoCaoCongNo.DataSource = tb;
        }

        private void BindingReportCongNo()
        {
            //Dao dao = new Dao();
            //BindingSource bs = new BindingSource();
            //var inv = dao.SelectInvoice(invoiceType);
            //bs.DataSource = inv;
            //gridControlBaoCaoCongNo.DataSource = bs;
            gridColumnCode.FieldName = "code";
            gridColumnAirlineCode.FieldName = "airline_code";
            gridColumnJurneyCode.FieldName = "journey_code";
            gridColumnInvoiceDate.FieldName = "invoiced_date";
            gridColumnCustomerCode.FieldName = "customer_code";
            gridColumnCustomerName.FieldName = "customer_name";
            gridColumnCustomerAddress.FieldName = "customer_address";
            gridColumnCustomerPhone.FieldName = "mobile";
            gridColumnSaleman.FieldName = "saleman";
            gridColumnDescription.FieldName = "description";
            gridColumnAmount.FieldName = "amount";
            gridColumnCommission.FieldName = "commission";
            gridColumnTotalAmount.FieldName = "total_amount";
            gridColumnPaidAmount.FieldName = "paid_amount";
            gridColumnCreateDate.FieldName = "created_date";
            gridColumnPassengerName.FieldName = "passenger_name";

        }


        private void FormReportCongNo_Load(object sender, EventArgs e)
        {
            Dao dao = new Dao();
            gridLookUpEditCustomer.Properties.DataSource = Dao.SelectCustomer();
            gridLookUpEditCustomer.Properties.DisplayMember = "name";
            gridLookUpEditCustomer.Properties.ValueMember = "code";
            GridColumn colCode = gridLookUpEditCustomer.Properties.View.Columns.AddField("code");
            colCode.VisibleIndex = 0;
            colCode.Width = 100;
            colCode.Caption = "Mã";
            GridColumn colName = gridLookUpEditCustomer.Properties.View.Columns.AddField("name");
            colName.VisibleIndex = 1;
            colName.Width = 100;
            colName.Caption = "Tên";
            GridColumn colAddr = gridLookUpEditCustomer.Properties.View.Columns.AddField("address");
            colAddr.VisibleIndex = 2;
            colAddr.Width = 120;
            colAddr.Caption = "Địa chỉ";
            GridColumn colTelephone = gridLookUpEditCustomer.Properties.View.Columns.AddField("telephone");
            colTelephone.VisibleIndex = 3;
            colTelephone.Width = 120;
            colTelephone.Caption = "Số điện thoại";
            GridColumn colMobile = gridLookUpEditCustomer.Properties.View.Columns.AddField("mobile");
            colMobile.VisibleIndex = 4;
            colMobile.Width = 120;
            colMobile.Caption = "Số DĐ";
            GridColumn colDesc = gridLookUpEditCustomer.Properties.View.Columns.AddField("description");
            colDesc.VisibleIndex = 5;
            colDesc.Width = 120;
            colDesc.Caption = "Diễn giải";

            //gridLookUpEditCustomer.Properties.View.FixedLineWidth=true;
            gridLookUpEditCustomer.Properties.View.OptionsView.ColumnAutoWidth = false;
            dFromDate.EditValue= new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            dToDate.EditValue = DateTime.Now;

            CreateGrid();
            BindingReportCongNo();

        }

        private void hdtManageControl1_HdtEditButtonClick()
        {
            string code = "";
            if (gridViewBaoCaoCongNo.FocusedRowHandle != -1)
            {
                code = gridViewBaoCaoCongNo.GetRowCellValue(gridViewBaoCaoCongNo.FocusedRowHandle, "code").ToString();
                Presentation.OpenForm(MdiParent, "FormInvoice", EOperation.Edit, code);
            }
        }

        private void hdtManageControl1_HdtDeleteButtonClick()
        {
            Dao dao = new Dao();
            string code = "";
            if (gridViewBaoCaoCongNo.FocusedRowHandle != -1)
            {
                code = gridViewBaoCaoCongNo.GetRowCellValue(gridViewBaoCaoCongNo.FocusedRowHandle, "code").ToString();
                if (MessageBox.Show("Bạn có muốn xóa Hóa đơn này: " + code, "thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Boolean flag = Dao.DeleteInvoice(code);
                    if (flag == true)
                    {
                        MessageBox.Show("Xóa thành công Hóa đơn: " + code);
                        FormReportCongNo_Load(null, EventArgs.Empty);
                    }
                }
            }
        }

        private void hdtManageControl1_HdtCloseButtonClick()
        {

        }

        private void hdtManageControl1_HdtExportButtonClick()
        {

        }

        private void hdtManageControl1_HdtImportButtonClick()
        {

        }
      
        void GetItemPrice(string journeyCode, string airlineCode)
        {
            Dao dao = new Dao();
            Item item = dao.SelectItemByJourneyAndAirline(journeyCode,airlineCode);
            if (item == null)
            {
                MessageBox.Show("Chọn lại hành trình và hãng hàng không");
                return;
            }
            gridViewBaoCaoCongNo.SetRowCellValue(gridViewBaoCaoCongNo.FocusedRowHandle,"sale_price", item.sale_price);

        }

        private void gridViewInvoiceDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int quantity = 0;
            decimal unitPrice = 0;
            decimal lineCommission = 0;
            decimal lineAmount = 0;
            decimal lineTotalAmount = 0;
            decimal lineServiceAmount = 0;
            switch(e.Column.FieldName.ToString())
            {
                case "depart_date":
                    break;

                case "return_date":
                    DateTime dReturnDate = DateTime.Parse( gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "return_date").ToString());
                    DateTime dDepartDate = DateTime.Parse(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "depart_date").ToString());
                    if (dReturnDate < dDepartDate)
                    {
                        XtraMessageBox.Show("[Ngày đến] Invalid Value");
                        gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "return_date", dDepartDate);
                    }
                    break;

                case "invoice_code":
                    break;
                case "item_code":
                    break;
                case "item_name":
                    break;
                case "journey_code":
                    break;

                case "airline_code":
                    string journeyCode = gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "journey_code").ToString();
                    string airlineCode = gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "airline_code").ToString();

                    if (journeyCode != null && airlineCode != null && journeyCode != string.Empty && airlineCode != string.Empty)
                    {
                        GetItemPrice(journeyCode, airlineCode); // lay don gia
                    }

                    goto case "currency_code";
                    //break;

                case "ticket_code":
                    break;

                case "currency_code":
                    //decimal rate = 1;
                    //Dao dao = new Dao();
                    ////DateTime invoiceDate = DateTime.Parse (txtInvoiceDate.EditValue.ToString());
                    //string airline = gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "airline_code").ToString();
                    //string currency = gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "currency_code").ToString();
                    //rate = dao.SelectRateWithCurrencyCode(airline, currency, invoiceDate.Date );
                    //if (currency == "VND")
                    //    rate = 1;
                    
                    //gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "rate", rate);
                    //goto case "sale_price";
                    break;

                case "quantity":
                case"commission"://giam gia cho khach hang
                case"sale_price":
                    quantity =int.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "quantity").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "quantity")).ToString())  ;
                    unitPrice=decimal.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "sale_price").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "sale_price")).ToString());
                    lineCommission = decimal.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "commission").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "commission")).ToString()); 

                    lineAmount =  unitPrice - lineCommission;// amount = sales_price - comission
                    gridViewBaoCaoCongNo.SetRowCellValue(gridViewBaoCaoCongNo.FocusedRowHandle, "amount", lineAmount);

                    lineServiceAmount = decimal.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "status_amount").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "status_amount")).ToString());
                    lineTotalAmount = lineAmount*quantity ; //+ lineServiceAmount;
                    gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "amount": // amount =  Sale_price - commission
                    quantity = int.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "quantity").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "quantity")).ToString());
                    lineServiceAmount = decimal.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "status_amount").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "status_amount")).ToString());
                    lineAmount = decimal.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "amount").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "amount")).ToString());
                    lineTotalAmount = lineAmount * quantity;//lineAmount + lineServiceAmount;
                    gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "service_fee": 
                case "status_quantity":
                    int status_quantity = int.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "status_quantity").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "status_quantity")).ToString());
                    decimal service_fee = decimal.Parse(Common.IIF(gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "service_fee").ToString() == "", 0, gridViewBaoCaoCongNo.GetRowCellValue(e.RowHandle, "service_fee")).ToString());
                    lineServiceAmount = status_quantity * service_fee;
                    gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "status_amount", lineServiceAmount);
                   
                    //lineAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount")).ToString());
                    //lineTotalAmount = lineAmount + lineServiceAmount;
                    //gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "status_amount": // service_fee*status_quantity
                    //lineServiceAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount")).ToString());
                    //lineAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount")).ToString());
                    //lineTotalAmount = lineAmount + lineServiceAmount;
                    //gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "total_amount": // Total_amount = amount + status_amount
                    break;

                case "airline_service_fee":
                    break;

                case "airline_commission":
                    break;

                case "customer":
                    break;

                case "customer_phone":
                    break;

                case "customer_email":
                    break;

                case "customer_id_card":
                    break;
            }
        }

        private void gridViewInvoiceDetail_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            //e.RowHandle 
            gridViewBaoCaoCongNo.SetRowCellValue(gridViewBaoCaoCongNo.FocusedRowHandle, "depart_date", DateTime.Now );
            gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "return_date", DateTime.Now);
            gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "currency_code", "VND");
            gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "rate", 1);
            gridViewBaoCaoCongNo.SetRowCellValue(e.RowHandle, "quantity", 1);
        }

        #region sub Menu
        class RowInfo
        {
            public RowInfo(GridView view, int rowHandle)
            {
                this.RowHandle = rowHandle;
                this.View = view;
            }
            public GridView View;
            public int RowHandle;
        }

        void OnAddRowClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.AddNewRow();
        }
        DXMenuItem CreateRowMenuAddRow(GridView view, int rowHandle)
        {
            DXMenuItem itemMenu = new DXMenuItem("&Thêm dòng", new EventHandler(OnAddRowClick));
            itemMenu.Tag = new RowInfo(view, rowHandle);
            return itemMenu;
        }

        DXMenuCheckItem CreateMergingEnabledMenuItem(GridView view, int rowHandle)
        {
            DXMenuCheckItem checkItem = new DXMenuCheckItem("&Merging Enabled",
            view.OptionsView.AllowCellMerge, null, new EventHandler(OnMergingEnabledClick));
            checkItem.Tag = new RowInfo(view, rowHandle);
            return checkItem;
        }

        //The handler for the MergingEnabled menu item
        void OnMergingEnabledClick(object sender, EventArgs e)
        {
            DXMenuCheckItem item = sender as DXMenuCheckItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.OptionsView.AllowCellMerge = item.Checked;
        }

        // Create a submenu with a single DeleteRow item.
        DXMenuItem CreateRowMenuDeleteRow(GridView view, int rowHandle)
        {
            DXMenuItem itemMenu = new DXMenuItem("&Xoá dòng", new EventHandler(OnDeleteRowClick));
            itemMenu.Tag = new RowInfo(view, rowHandle);//"adadad";       
            return itemMenu;
        }

        ////The handler for the DeleteRow menu item
        void OnDeleteRowClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.DeleteRow(info.RowHandle);
        }
        #endregion

        private void btnXem_Click(object sender, EventArgs e)
        {
            DateTime fromDate = dFromDate.DateTime;
            DateTime toDate = dToDate.DateTime;
            string CustomerCode = gridLookUpEditCustomer.EditValue.ToString();
            if (CustomerCode=="[All]")
                CustomerCode="";
            gridControlBaoCaoCongNo.DataSource = Dao.BaoCaoBanHang(fromDate, toDate, CustomerCode);
        }

       
        //private void gridViewInvoiceDetail_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        //{
        //    GridView view = sender as GridView;
        //    // Check whether a row is right-clicked.
        //    if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Row)
        //    {
        //        int rowHandle = e.HitInfo.RowHandle;
        //        // Delete existing menu items, if any.
        //        e.Menu.Items.Clear();
        //        // Add a submenu with a single menu item.
        //        e.Menu.Items.Add(CreateRowMenuAddRow(view, rowHandle));
        //        e.Menu.Items.Add(CreateRowMenuDeleteRow(view, rowHandle));
        //        // Add a check menu item.
        //        //DXMenuItem item = CreateMergingEnabledMenuItem(view, rowHandle);
        //        //item.BeginGroup = true;
        //        //e.Menu.Items.Add(item);
        //    }
        //}



        
    }
}
